'use client';

import React, { useEffect, useRef, useState } from 'react';
import { 
  createChart, 
  IChartApi, 
  CandlestickData,
  HistogramData,
  ColorType,
  LineStyle,
  UTCTimestamp
} from 'lightweight-charts';
import { useMarketData } from '../hooks/useMarketData';

interface TradingViewLightChartProps {
  symbol: string;
}

export default function TradingViewLightChart({ symbol }: TradingViewLightChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const candlestickSeriesRef = useRef<any>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const volumeSeriesRef = useRef<any>(null);
  const [timeframe, setTimeframe] = useState('4h');
  const [isLoading, setIsLoading] = useState(true);

  // 使用市场数据hook
  const { klineData, loading: dataLoading } = useMarketData({
    symbol,
    interval: timeframe,
    dataSource: 'mock',
    enableRealtime: true
  });

  // 初始化图表
  useEffect(() => {
    if (!chartContainerRef.current) return;

    // 创建图表
    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { type: ColorType.Solid, color: '#ffffff' },
        textColor: '#333',
      },
      grid: {
        vertLines: {
          color: '#f0f0f0',
          style: LineStyle.Solid,
        },
        horzLines: {
          color: '#f0f0f0',
          style: LineStyle.Solid,
        },
      },
      rightPriceScale: {
        borderColor: '#e0e0e0',
        scaleMargins: {
          top: 0.1,
          bottom: 0.3,
        },
      },
      timeScale: {
        borderColor: '#e0e0e0',
        timeVisible: true,
        secondsVisible: false,
      },
      crosshair: {
        mode: 1,
      },
      width: chartContainerRef.current.clientWidth,
      height: 500,
    });

    // 使用正确的v5 API添加系列
    try {
      // 创建K线序列 - lightweight-charts 正确用法
      // const candlestickSeries = chart.addCandlestickSeries({
      //   upColor: '#02C076',
      //   downColor: '#F6465D',
      //   borderDownColor: '#F6465D',
      //   borderUpColor: '#02C076',
      //   wickDownColor: '#F6465D',
      //   wickUpColor: '#02C076',
      // });

      // // 创建成交量序列 - lightweight-charts 正确用法
      // const volumeSeries = chart.addHistogramSeries({
      //   priceFormat: {
      //     type: 'volume',
      //   },
      //   priceScaleId: '',
      //   scaleMargins: {
      //     top: 0.7,
      //     bottom: 0,
      //   },
      // });

      // // 设置成交量颜色
      // if (volumeSeries && volumeSeries.priceScale) {
      //   volumeSeries.priceScale().applyOptions({
      //     scaleMargins: {
      //       top: 0.7,
      //       bottom: 0,
      //     },
      //   });
      // }

      // chartRef.current = chart;
      // candlestickSeriesRef.current = candlestickSeries;
      // volumeSeriesRef.current = volumeSeries;
    } catch (error) {
      console.error('创建图表系列时出错:', error);
    }

    // 响应式处理
    const handleResize = () => {
      if (chartContainerRef.current && chart) {
        chart.applyOptions({ 
          width: chartContainerRef.current.clientWidth,
          height: 500
        });
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (chart) {
        chart.remove();
      }
    };
  }, []);

  // 更新图表数据
  useEffect(() => {
    if (!candlestickSeriesRef.current || !volumeSeriesRef.current || !klineData || klineData.length === 0) {
      return;
    }

    try {
      // 转换K线数据格式
      const candleData: CandlestickData[] = klineData.map(candle => ({
        time: Math.floor(candle.time / 1000) as UTCTimestamp,
        open: candle.open,
        high: candle.high,
        low: candle.low,
        close: candle.close,
      }));

      // 转换成交量数据格式
      const volumeData: HistogramData[] = klineData.map(candle => ({
        time: Math.floor(candle.time / 1000) as UTCTimestamp,
        value: candle.volume,
        color: candle.close > candle.open ? '#02C076' : '#F6465D',
      }));

      // 设置数据
      candlestickSeriesRef.current.setData(candleData);
      volumeSeriesRef.current.setData(volumeData);

      // 适配可见范围
      if (chartRef.current && candleData.length > 0) {
        chartRef.current.timeScale().fitContent();
      }

      setIsLoading(false);
    } catch (error) {
      console.error('更新图表数据时出错:', error);
    }
  }, [klineData]);

  // 时间周期选项
  const timeframes = [
    { label: '1m', value: '1m' },
    { label: '5m', value: '5m' },
    { label: '15m', value: '15m' },
    { label: '1h', value: '1h' },
    { label: '4h', value: '4h' },
    { label: '1d', value: '1d' },
    { label: '1w', value: '1w' },
  ];

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 h-full flex flex-col">
      {/* 图表工具栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-4">
          <h3 className="font-semibold text-gray-900 dark:text-white">
            K线图表
          </h3>
          <div className="flex items-center space-x-1 text-sm text-gray-600 dark:text-gray-400">
            <span>当前周期: {timeframe}</span>
            <span>|</span>
            <span>交易对: {symbol}</span>
          </div>
        </div>

        {/* 时间周期选择器 */}
        <div className="flex items-center space-x-1">
          {timeframes.map((tf) => (
            <button
              key={tf.value}
              onClick={() => setTimeframe(tf.value)}
              className={`px-3 py-1 text-sm rounded transition-colors ${
                timeframe === tf.value
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600'
              }`}
            >
              {tf.label}
            </button>
          ))}
        </div>
      </div>

      {/* 图表容器 */}
      <div className="flex-1 relative">
        {(isLoading || dataLoading) && (
          <div className="absolute inset-0 flex items-center justify-center bg-white/80 dark:bg-gray-800/80 z-10">
            <div className="flex items-center space-x-2">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
              <span className="text-gray-600 dark:text-gray-400">加载图表数据...</span>
            </div>
          </div>
        )}
        <div 
          ref={chartContainerRef} 
          className="w-full h-full"
          style={{ minHeight: '500px' }}
        />
      </div>

      {/* 图表说明 */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750">
        <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-green-500 rounded"></div>
              <span>涨幅</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-red-500 rounded"></div>
              <span>跌幅</span>
            </div>
          </div>
          <div className="text-right">
            <span>TradingView Lightweight Charts</span>
          </div>
        </div>
      </div>
    </div>
  );
}
